from __future__ import absolute_import
from forest.api import Command, get_tool
import platform
import logging
from os.path import join
import solv
import sys

from pkgr.pkgr import Pkgr
from pkgr.reporepomd import RepoRepomd

logger = logging.getLogger('commands.pkgr.Prepare')

class Prepare(Command):

    __register__= 'commands.pkgr.Prepare'

    def run(self, config):
        # XXX rename yum to pkgr in treefiles and here

        self.args = config.get('yum')

        tempdir = config.get_build_root()

        pkgrtempdir = join(tempdir, "pkgr")

        logger.debug('Using pkgr temp dir %s', pkgrtempdir)

        installtree = config.get_install_root()
        get_tool('system.mkdir')(join(installtree, 'tmp'))

        arch = config.get('yum.architecture', 'i386')
        curr_arch, linkage = platform.architecture()

        translate_arch = { '32bit' : 'i386', '64bit' : 'x86_64'}
        if arch != translate_arch.get(curr_arch, curr_arch):
            raise Exception("Forest cannot build images in an architecture different from this system: {0} != {1}".format(arch, curr_arch))

        pkgrcache = join(installtree, 'var', 'lib', 'pkgr')
        pkgr = Pkgr()
        pkgr.set_arch(arch)
        pkgr.set_root(installtree)
        pkgr.set_cache_dir(pkgrcache)


        # load all enabled repos into the pool
        configured_repos = []
        for repo in config.get_resources().iter_by_type('repository'):
            repoattr = {
                'enabled': True,
                'priority': 99,
                'autorefresh': True,
                'type': 'repomd',
                'metadata_expire': 300
            }

            url = repo.get_url()
            url = url.replace('$release', str(config.get('yum.release')))
            url = url.replace('$architecture', arch)


            #XXX hacky, should be fixed
            repoattr[repo.get_type()] = url

            cfg_repo = RepoRepomd(repo.get_name(), 'repomd', repoattr)

            cachedirbase = join(config.get_build_root(), 'pkgr')
            cfg_repo.set_cache_dir(cachedirbase)

            cfg_repo.set_url(repo.get_type(), url)
            configured_repos.append(cfg_repo)

            if repo.get_embed():
                repo_f_name = '.'.join([repo.get_name_subs(), 'repo'])
                repo_base_path = join(installtree, 'etc', 'yum.repos.d')
                full_resource_path = join(repo_base_path, repo_f_name)

                get_tool('files.write')(full_resource_path, repo.serialize())
        if installtree != '/':
            get_tool('system.bindmount')('/dev', join(installtree, 'dev'))
            get_tool('system.mount')('none', join(installtree, 'proc'), 'proc')
            get_tool('system.mount')('none', join(installtree, 'sys'), 'sysfs')

        sysrepo = pkgr.get_sysrepo()



        for repo in configured_repos:
            if repo.get_enabled():

                pkgr.add_repo(repo)





        config.set('_pkgr', pkgr)

        #TRY:
        #pool = pkgr.get_solv_pool()
        #for solvid in pkgr.search('emacs'):
        #    print " - %s [%s]: %s" % (pool.solvid2str(solvid), pool.solvables[solvid].repo.name, pool.lookup_str(solvid, solv.SOLVABLE_SUMMARY))
        #sys.exit(0)
        #raise Exception('just raising for testing')
